//
//  WH_AppTools.m
//  App_6.23
//
//  Created by wanghao on 16/6/29.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_AppTools.h"

@implementation WH_AppTools

+(void)getDataWithURL:(NSString *)urlStr block:(AppToolsBlock)block error:(AppToolsErrorBlock)errorBlock
{
    
    NSError *error2 = nil;
    NSString *urlEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    [manager GET:urlEncode parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //block回调
        block(responseObject);
//        NSString *path = [NSString stringWithFormat:@"%ld.plist", [urlStr hash]];
//        // 存储的沙盒路径
//        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//        // 归档
//        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败==== %@",error);
        errorBlock(error2);
        
        // 缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [urlStr hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        block(result);
        
        
    }];
    
}

+ (void)postUrl:(NSString *)url
           body:(id)body
         result:(HXResult)result
   requestStyle:(HXRequestStyle)requestStyle
     headerFile:(NSDictionary *)headerFile
        success:(void (^)(id result))success
        failure:(void (^)(NSError *error))failure
{
    // 1.获取网络请求管理类
    //3.0这个声明
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2.网络请求请求体Body的类型
    switch (requestStyle) {
        case HXRequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case HXRequestString:
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError *__autoreleasing *error) {
                return parameters;
            }];
            break;
            
        default:
            break;
    }
    
    // 3.为网络请求加请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    // 4.网络请求返回值的数据类型
    switch (result) {
        case HXData:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case HXJSON:
            break;
        case HXXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    
    // 5.设置网络请求返回值支持的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain",@"application/x-javascript", nil]];
    
    // 6.发送网络请求
    [manager POST:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            success(responseObject);
            
            NSString *path = [NSString stringWithFormat:@"%ld.plist", [body hash]];
            // 存储的沙盒路径
            NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            // 归档
            [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];

            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        failure(error);
    
            
        //缓存的文件夹
        NSString *path = [NSString stringWithFormat:@"%ld.plist", [body hash]];
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
        success(result);
        
    }];
}

//label高度
+(CGSize)labelRectWithSize:(CGSize)size
                 LabelText:(NSString *)labelText
                      Font:(UIFont *)font{
    
    NSDictionary  *dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
    CGSize actualsize = [labelText boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    
    return actualsize;
    
    
}
+(void)changeColor:(NSString *)title color:(UIColor *)color xx:(NSString *)cc nn:(UILabel *)moreTitleLabel{
    if (cc.length == 0 || title.length == 0) {
        
        cc = @"loading...";
        title = @"loading...";
    }

    // 设置标签文字
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:title];
    // 获取标红的位置和长度
    NSRange range = [title rangeOfString:cc];//获取需要变量文字的文字
    [att addAttribute:NSForegroundColorAttributeName value:color range:range];
    // 显示在Label上
    moreTitleLabel.attributedText = att;
    
}
+ (NSString *)currentData{
    
    //获取系统当前时间
    NSDate *currentData = [NSDate date];
    //设置时间格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    //data转化成字符串
    NSString *dateStr = [formatter stringFromDate:currentData];
    return dateStr;
}

+ (NSString *)intervalSinceNow: (NSString *) theDate
{
    NSArray *timeArray=[theDate componentsSeparatedByString:@"."];
    theDate=[timeArray objectAtIndex:0];
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate date];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=late-now;
    
    if (cha/3600<1) {
        timeString = [NSString stringWithFormat:@"%f", cha];
        timeString = [timeString substringToIndex:timeString.length-7];
        //timeString=[NSString stringWithFormat:@"剩余%@分", timeString];
        
    }
    if (cha/3600>1&&cha/86400<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"剩余%@小时", timeString];
    }
    if (cha/86400>1)
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"剩余%@天", timeString];
        
    }
    return timeString;
}
+ (NSString *)intervalFromLastDate: (NSString *) dateString1  toTheDate:(NSString *) dateString2
{
    NSArray *timeArray1=[dateString1 componentsSeparatedByString:@"."];
    dateString1=[timeArray1 objectAtIndex:0];
    
    NSArray *timeArray2=[dateString2 componentsSeparatedByString:@"."];
    dateString2=[timeArray2 objectAtIndex:0];
    
    NSLog(@"%@.....%@",dateString1,dateString2);
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *d1=[date dateFromString:dateString1];
    
    NSTimeInterval late1=[d1 timeIntervalSince1970]*1;
    
    NSDate *d2=[date dateFromString:dateString2];
    
    NSTimeInterval late2=[d2 timeIntervalSince1970]*1;
    
    NSTimeInterval cha=late2-late1;
    
    //    秒
    NSString *sen = [NSString stringWithFormat:@"%f", cha];
    
    
    return sen;
}
@end
